package io.zhiller.libdemos

import android.content.Context
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.lifecycle.viewmodel.compose.viewModel
import io.zhiller.commonlib.data.models.PermissionModel
import io.zhiller.commonlib.data.models.PermissionStatus
import io.zhiller.commonlib.utils.android.PermissionUtils
import io.zhiller.libdemos.di.viewmodel.PermissionVM

import io.zhiller.libdemos.ui.theme.LibDemosTheme


class MainActivity : ComponentActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    enableEdgeToEdge()
    setContent {
      LibDemosTheme {
        Scaffold(modifier = Modifier.fillMaxSize()) { it ->
          it.calculateTopPadding()
          TestComponent(this)
        }
      }
    }
  }
}

@Composable
fun TestComponent(context: Context) {

  val permissionVM: PermissionVM = viewModel()

  Column (
    modifier = Modifier.fillMaxSize(),
    verticalArrangement = Arrangement.Center,
    horizontalAlignment = Alignment.CenterHorizontally
  ){
    RequestSinglePermission(context, permissionVM.cameraPermission){}
    RequestMultiPermissions(context, permissionVM.multiPermissions){}
  }
}

/**
 * 请求单个权限的函数
 *
 * @param context Android 上下文，用于检查权限状态和显示Toast提示
 * @param permission 一个PermissionModel对象，包含了权限的相关信息
 * @param content 一个可组合的lambda函数，用于在请求权限前后进行UI更新
 *
 * 此函数用于请求Android权限，根据权限的状态（未请求、已授予、被拒绝、永久拒绝）来执行不同的操作
 * 它使用了一个Launcher来处理权限请求的结果，并在适当的时候显示对话框提示用户
 */
@Composable
fun RequestSinglePermission(
  context: Context,
  permission: PermissionModel,
  content: @Composable () -> Unit
) {
  // 用于记住是否应该显示权限永久拒绝的对话框
  val isShowPermissionDialog = remember {
    mutableStateOf(false)
  }

  // 记住一个Launcher，用于处理权限请求的结果
  val permissionLauncher = rememberLauncherForActivityResult(
    contract = ActivityResultContracts.RequestPermission(),
    onResult = { isGranted ->
      // 根据用户是否授权，更新权限的状态
      permission.permissionsStatus =
        if (isGranted) PermissionStatus.Granted
        else if (permission.permissionsStatus != PermissionStatus.PermanentlyDenied) PermissionStatus.PermanentlyDenied
        else PermissionStatus.Denied
    }
  )

  // 点击按钮时请求权限
  Button(onClick = {
    permission.permissionsStatus = PermissionUtils.checkPermission(context, permission)
    when (permission.permissionsStatus) {
      PermissionStatus.NotAsked, PermissionStatus.Denied -> {
        // 如果权限未请求或被拒绝，发起权限请求并显示提示
        permissionLauncher.launch(permission.permission)
        Toast.makeText(context, permission.permissionDeniedDetail, Toast.LENGTH_SHORT).show()
      }

      PermissionStatus.Granted -> {
        // 如果权限已被授予，显示授权成功的提示
        Toast.makeText(context, permission.permissionGrantedDetail, Toast.LENGTH_SHORT).show()
      }

      PermissionStatus.PermanentlyDenied -> {
        // 如果权限被永久拒绝，显示对话框提示用户前往设置界面开启权限
        isShowPermissionDialog.value = true
      }

      else -> {}
    }
  }) {
    Text(text = "请求权限")
  }

  // 如果需要显示权限永久拒绝的对话框，则显示
  if (isShowPermissionDialog.value) {
    AlertDialog(
      onDismissRequest = {
        isShowPermissionDialog.value = false
      },
      confirmButton = {
        Button(onClick = {
          PermissionUtils.openAppSettings(context, context.packageName)
          isShowPermissionDialog.value = false
        }) {
          Text(text = "前往设置界面")
        }
      },
      title = {
        Text(text = "权限禁止")
      },
      text = {
        Text(text = permission.permissionPermanentlyDeniedDetail)
      }
    )
  }
}


@Composable
fun RequestMultiPermissions(
  context: Context,
  permissions: List<PermissionModel>,
  content: @Composable () -> Unit
) {
  val isShowPermissionDialog = remember { mutableStateOf(false) }
  var deniedPermissionsList: MutableList<String>

  val permissionLauncher = rememberLauncherForActivityResult(
    contract = ActivityResultContracts.RequestMultiplePermissions(),
    onResult = { permissionRes ->
      permissions.forEach { p ->
        p.permissionsStatus = permissionRes[p.permission]?.let { isGranted ->
          if (isGranted) PermissionStatus.Granted
          else if (p.permissionsStatus != PermissionStatus.PermanentlyDenied) PermissionStatus.PermanentlyDenied
          else PermissionStatus.Denied
        } ?: p.permissionsStatus
      }
    }
  )

  Button(onClick = {
    permissionLauncher.launch(permissions.map { it.permission }.toTypedArray())
    deniedPermissionsList = PermissionUtils.checkMultiPermissions(context, permissions).toMutableList()
    if(deniedPermissionsList.isNotEmpty()) {
      isShowPermissionDialog.value = true
      Toast.makeText(context, "您有${deniedPermissionsList.size}个权限禁止", Toast.LENGTH_SHORT).show()
    }
    else Toast.makeText(context, "权限都被许可或仅一次拒绝", Toast.LENGTH_SHORT).show()
  }) {
    Text(text = "请求多个权限")
  }

  if(isShowPermissionDialog.value){
    AlertDialog(
      onDismissRequest = {
        isShowPermissionDialog.value = false
      },
      confirmButton = {
        Button(onClick = {
          PermissionUtils.openAppSettings(context, context.packageName)
          isShowPermissionDialog.value = false
        }) {
          Text(text = "前往设置界面")
        }
      },
      title = {
        Text(text = "权限禁止")
      },
      text = {
        Text(text = "您有些权限禁止，请前往设置界面打开！！！")
      }
    )
  }
}